package com.echo.servlet;

import com.echo.entity.Category;
import com.echo.service.CategoryService;
import com.echo.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 管理员分类管理Servlet
 * 处理分类的增删改查操作
 */
@WebServlet({"/admin/category", "/admin/categoryAdd", "/admin/categoryList.html", "/echo-network/admin/category", "/echo-network/admin/categoryAdd", "/echo-network/admin/categoryList.html"})
public class AdminCategoryServlet extends BaseServlet {
    private CategoryService categoryService = new CategoryService();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 检查管理员权限，所有管理员分类操作都需要管理员权限
        if (!checkAdmin(req, resp)) {
            return;
        }
        
        // 检查请求路径，如果是直接访问categoryAddOrEdit，则显示添加页面
        String requestURI = req.getRequestURI();
        if (requestURI.endsWith("/categoryAdd")) {
            String idParam = req.getParameter("id");
            if (idParam != null && !idParam.isEmpty()) {
                // 如果有id参数，则显示编辑页面
                editCategoryPage(req, resp);
            } else {
                // 没有id参数，显示添加页面
                req.setAttribute("isEdit", false);
                forward(req, resp, "/admin/categoryAdd.html");
            }
            return;
        } else if (requestURI.endsWith("/categoryList.html")) {
            // 如果直接访问categoryList.html，执行显示分类列表的方法
            showCategoryList(req, resp);
            return;
        }
        
        String action = req.getParameter("action");
        if (action == null) {
            showCategoryList(req, resp); // 默认显示分类列表
        } else if ("list".equals(action)) {
            showCategoryList(req, resp);
        } else if ("addPage".equals(action)) {
            // 跳转到添加分类页面
            req.setAttribute("isEdit", false);
            forward(req, resp, "/admin/categoryAdd.html");
        } else if ("editPage".equals(action)) {
            // 跳转到编辑分类页面
            editCategoryPage(req, resp);
        } else if ("listJson".equals(action)) {
            // 获取分类列表JSON数据
            getCategoryListJson(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 检查管理员权限，所有管理员分类操作都需要管理员权限
        if (!checkAdmin(req, resp)) {
            return;
        }
        
        // 无论请求路径如何，都统一处理action参数
        String action = req.getParameter("action");
        if (action == null) {
            showCategoryList(req, resp);
        } else if ("add".equals(action)) {
            addCategory(req, resp);
        } else if ("update".equals(action) || "edit".equals(action)) {
            // 同时支持action=update和action=edit，以兼容前端表单
            updateCategory(req, resp);
        } else if ("delete".equals(action)) {
            deleteCategory(req, resp);
        }
    }

    /**
     * 显示分类列表
     */
    private void showCategoryList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Category> categories = categoryService.getAllCategories();
        req.setAttribute("categories", categories);
        
        // 从URL参数中获取消息并设置到请求属性中
        String message = req.getParameter("message");
        String messageType = req.getParameter("messageType");
        if (message != null) {
            req.setAttribute("message", message);
            req.setAttribute("messageType", messageType != null ? messageType : "info");
        }
        
        // 使用自定义方法渲染页面，避免循环转发
        forward(req, resp, "/admin/categoryList.html");
    }

    /**
     * 跳转到编辑分类页面
     */
    private void editCategoryPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String idStr = req.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            try {
                int id = Integer.parseInt(idStr);
                Category category = categoryService.getCategoryById(id);
                if (category != null) {
                    req.setAttribute("category", category);
                    forward(req, resp, "/admin/categoryEdit.html");
                    return;
                }
            } catch (NumberFormatException e) {
                // 处理数字格式异常
            }
        }
        // 如果参数错误或分类不存在，重定向到分类列表
        resp.sendRedirect(req.getContextPath() + "/admin/categoryList.html");
    }

    /**
     * 获取分类列表JSON数据
     */
    private void getCategoryListJson(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Category> categories = categoryService.getAllCategories();
        ResponseUtils.setJsonResponse(resp);
        // 简单的JSON序列化
        StringBuilder jsonBuilder = new StringBuilder("[");
        for (int i = 0; i < categories.size(); i++) {
            Category category = categories.get(i);
            jsonBuilder.append("{\"categoryId\":")
                      .append(category.getCategoryId())
                      .append(",\"categoryName\":\"")
                      .append(category.getCategoryName().replace("\"", "\\\\\""))
                      .append("\",\"categoryDesc\":\"")
                      .append(category.getCategoryDesc() != null ? category.getCategoryDesc().replace("\"", "\\\\\"").replace("\n", "\\n") : "")
                      .append("\",\"createTime\":\"")
                      .append(category.getCreateTime())
                      .append("\"}");
            if (i < categories.size() - 1) {
                jsonBuilder.append(",");
            }
        }
        jsonBuilder.append("]");
        resp.getWriter().write(jsonBuilder.toString());
    }

    /**
     * 添加分类
     */
    private void addCategory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String categoryName = req.getParameter("categoryName");
        String categoryDesc = req.getParameter("categoryDesc");
        
        // 验证参数
        if (categoryName == null || categoryName.trim().isEmpty()) {
            req.setAttribute("message", "分类名称不能为空");
            req.setAttribute("messageType", "error");
            req.setAttribute("isEdit", false);
            forward(req, resp, "/admin/categoryAdd.html");
            return;
        }
        
        try {
            // 检查分类名称是否已存在
            if (categoryService.isCategoryNameExists(categoryName)) {
                req.setAttribute("message", "分类名称已存在");
                req.setAttribute("messageType", "error");
                req.setAttribute("isEdit", false);
                forward(req, resp, "/admin/categoryAdd.html");
                return;
            }
            
            // 创建分类对象
            Category category = new Category();
            category.setCategoryName(categoryName.trim());
            category.setCategoryDesc(categoryDesc != null ? categoryDesc.trim() : "");
            // 设置创建时间和更新时间
            Date now = new Date();
            category.setCreateTime(now);
            category.setUpdateTime(now);
            // 设置删除状态为未删除
            category.setIsDeleted(0);
            
            // 调用服务层添加分类
            int categoryId = categoryService.addCategory(category);
            
            if (categoryId > 0) {
                // 添加成功，在当前页面显示成功消息
                req.setAttribute("message", "分类添加成功");
                req.setAttribute("messageType", "success");
                req.setAttribute("isEdit", false);
                forward(req, resp, "/admin/categoryAdd.html");
            } else if (categoryId == -1) {
                // 分类名称已存在
                req.setAttribute("message", "分类名称已存在");
                req.setAttribute("messageType", "error");
                req.setAttribute("isEdit", false);
                forward(req, resp, "/admin/categoryAdd.html");
            } else {
                // 添加失败，返回添加页面并显示错误消息
                req.setAttribute("message", "分类添加失败，数据库操作错误");
                req.setAttribute("messageType", "error");
                req.setAttribute("isEdit", false);
                forward(req, resp, "/admin/categoryAdd.html");
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("message", "添加分类时发生错误：" + e.getMessage());
            req.setAttribute("messageType", "error");
            req.setAttribute("isEdit", false);
            forward(req, resp, "/admin/categoryAdd.html");
        }
    }

    /**
     * 更新分类
     */
    private void updateCategory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String idStr = req.getParameter("id");
        String categoryName = req.getParameter("categoryName");
        String categoryDesc = req.getParameter("categoryDesc");
        
        // 验证参数
        if (idStr == null || idStr.isEmpty() || categoryName == null || categoryName.trim().isEmpty()) {
            req.setAttribute("message", "分类ID和名称不能为空");
            req.setAttribute("messageType", "error");
            forward(req, resp, "/admin/categoryList.html");
            return;
        }
        
        try {
            int id = Integer.parseInt(idStr);
            
            // 检查分类是否存在
            Category existingCategory = categoryService.getCategoryById(id);
            if (existingCategory == null) {
                req.setAttribute("message", "分类不存在");
                req.setAttribute("messageType", "error");
                forward(req, resp, "/admin/categoryList.html");
                return;
            }
            
            // 检查新名称是否与其他分类重复
            if (!categoryName.trim().equals(existingCategory.getCategoryName()) && categoryService.isCategoryNameExists(categoryName.trim())) {
                req.setAttribute("message", "分类名称已存在");
                req.setAttribute("messageType", "error");
                req.setAttribute("isEdit", true);
                req.setAttribute("category", existingCategory);
                forward(req, resp, "/admin/categoryAdd.html");
                return;
            }
            
            // 更新分类信息
            existingCategory.setCategoryName(categoryName.trim());
            existingCategory.setCategoryDesc(categoryDesc != null ? categoryDesc.trim() : "");
            // 更新时间
            existingCategory.setUpdateTime(new Date());
            
            // 调用服务层更新分类
            boolean success = categoryService.updateCategory(existingCategory);
            
            // 根据更新结果处理响应
            if (success) {
                // 更新成功，在当前页面显示成功消息
                req.setAttribute("message", "分类更新成功");
                req.setAttribute("messageType", "success");
                req.setAttribute("isEdit", true);
                req.setAttribute("category", existingCategory);
                forward(req, resp, "/admin/categoryAdd.html");
            } else {
                // 更新失败，返回编辑页面并显示错误消息
                req.setAttribute("message", "分类更新失败，数据库操作错误");
                req.setAttribute("messageType", "error");
                req.setAttribute("isEdit", true);
                req.setAttribute("category", existingCategory);
                forward(req, resp, "/admin/categoryAdd.html");
            }
        } catch (NumberFormatException e) {
            req.setAttribute("message", "无效的分类ID");
            req.setAttribute("messageType", "error");
            forward(req, resp, "/admin/categoryList.html");
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("message", "更新分类时发生错误：" + e.getMessage());
            req.setAttribute("messageType", "error");
            forward(req, resp, "/admin/categoryList.html");
        }
    }

    /**
     * 删除分类
     */
    private void deleteCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idStr = req.getParameter("id");
        
        // 验证参数
        if (idStr == null || idStr.isEmpty()) {
            ResponseUtils.setJsonResponse(resp);
            resp.getWriter().write("{\"success\": false, \"message\": \"分类ID不能为空\"}");
            return;
        }
        
        try {
            int id = Integer.parseInt(idStr);
            
            // 调用服务层删除分类
            boolean success = categoryService.deleteCategory(id);
            
            // 返回成功响应
            ResponseUtils.setJsonResponse(resp);
            resp.getWriter().write("{\"success\": true, \"message\": \"分类删除成功\"}");
        } catch (NumberFormatException e) {
            ResponseUtils.setJsonResponse(resp);
            resp.getWriter().write("{\"success\": false, \"message\": \"无效的分类ID\"}");
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtils.setJsonResponse(resp);
            resp.getWriter().write("{\"success\": false, \"message\": \"分类删除失败\"}");
        }
    }
}